<template>


  <div class="common-layout">
    <el-container>
      <el-header style="height: 120px;">
        <el-form :inline="true" :model="paging" class="demo-form-inline">
          <el-form-item label="商品名称">
            <el-input v-model="paging.goodsName" clearable />
          </el-form-item>
          <el-form-item label="生产批次">
            <el-input v-model="paging.basicBatch" clearable />
          </el-form-item>
          <el-form-item label="保质期(天)">
            <el-input v-model="paging.basicExpiration" clearable />
          </el-form-item>
          <el-form-item label="生产许可证号">
            <el-input v-model="paging.basicLicense" clearable />
          </el-form-item>
          <el-form-item label="生产企业">
            <el-input v-model="paging.basicEnterprise" clearable />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="basicGet">查询</el-button>
          </el-form-item>
        </el-form>

      </el-header>
      <el-main>
        <div class="container">
          <!-- 商品列表区域 -->
          <el-card shadow="hover">
            <div class="card-header">
              <el-button type="primary" @click="handleAdd">
                <Plus style="width: 1em; height: 1em; margin-right: 8px" />新增
              </el-button>
              <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0"><el-icon>
                  <Delete />
                </el-icon>删除</el-button>



            </div>
            <div style="float: right;">
              <el-icon @click="refreshTable">
                <RefreshRight />
              </el-icon>
              <el-icon @click="handleSetting">
                <Setting />
              </el-icon>
              <el-icon @click="toggleMoreQuery">
                <Filter />
              </el-icon>
            </div>




            <el-table :data="tableData" @selection-change="handleSelectionChange" border style="width: 100%">
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" :index="indexMethod" />
              <!-- 商品名称列（带查询输入） -->
              <el-table-column prop="goodsName" label="商品名称">
                <template #header>
                  <el-input v-model="tableData.goodsName" placeholder="输入进行查询" clearable size="small"
                    style="width: 100%" />
                </template>
              </el-table-column>

              <!-- 生产批次列（带查询输入） -->
              <el-table-column prop="basicBatch" label="生产批次">
                <template #header>
                  <el-input v-model="tableData.basicBatch" placeholder="输入进行查询" clearable size="small"
                    style="width: 100%" />
                </template>
              </el-table-column>

              <!-- 保质期列（带查询输入） -->
              <el-table-column prop="basicExpiration" label="保质期(天)">
                <template #header>
                  <el-input v-model="tableData.basicExpiration" placeholder="输入进行查询" clearable size="small"
                    style="width: 100%" />
                </template>
              </el-table-column>

              <!-- 生产许可证号列（带查询输入） -->
              <el-table-column prop="basicLicense" label="生产许可证号">
                <template #header>
                  <el-input v-model="tableData.basicLicense" placeholder="输入进行查询" clearable size="small"
                    style="width: 100%" />
                </template>
              </el-table-column>

              <!-- 生产企业列（带查询输入） -->
              <el-table-column prop="basicEnterprise" label="生产企业">
                <template #header>
                  <el-input v-model="tableData.basicEnterprise" placeholder="输入进行查询" clearable size="small"
                    style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="completeness" label="信息完整度">
                <template #default="scope">
                  <span :style="{ color: scope.row.num === '1' ? 'green' : 'red' }">
                    {{ scope.row.num }}%
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button type="text" @click="handleDetail(scope.row.id, scope.row.basicBatch)">详情</el-button>
                  <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
                  <el-button type="text" @click="handleExportSource(scope.row.basicId)">导出溯源码</el-button>
                  <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="paging.pageIndex" v-model:page-size="paging.pageSize"
              :page-sizes="[10, 20]" layout="total, sizes, prev, pager, next, jumper" :total="paging.count"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页" />

          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>


  <!-- 新增弹窗 -->
  <el-dialog v-model="dialogFormVisible" title="新增溯源商品信息" width="50%">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="商品名称" prop="goodsId">
        <el-select v-model="form.goodsId" placeholder="请选择商品名称" filterable>
          <el-option v-for="item in goodsOptions" :key="item.id" :label="item.goodsName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次" prop="basicBatch">
        <el-input v-model="form.basicBatch" />
      </el-form-item>
      <el-form-item label="保质期(天)" prop="basicExpiration">
        <el-input v-model.number="form.basicExpiration" type="number" min="0" max="99999" />
      </el-form-item>
      <el-form-item label="生产许可证号" prop="basicLicense">
        <el-input v-model="form.basicLicense" />
      </el-form-item>
      <el-form-item label="生产企业" prop="basicEnterprise">
        <el-input v-model="form.basicEnterprise" />
      </el-form-item>
      <!-- 商品主图上传 -->
      <el-form-item label="商品主图" prop="basicPhoto">
        <div class="upload-container">
          <!-- 图片上传组件 -->
          <el-upload class="image-uploader" action="#" :file-list="fileList" :on-change="handleFileChange"
            :before-upload="beforeUpload" :on-remove="handleRemove" :http-request="handleUpload" :limit="1"
            :on-exceed="handleExceed" list-type="picture-card">
            <el-icon class="upload-icon">
              <Plus />
            </el-icon>
            <div class="upload-text">点击上传或拖拽文件到此处</div>
          </el-upload>

          
          <!-- 预览区域 -->
          <div v-if="previewUrl" class="preview-wrapper mt-3">
            <el-image :src="previewUrl" :alt="form.basicPhoto || '商品图片'" fit="contain" class="preview-img">
              <template #error>
                <div class="image-placeholder">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <!-- 上传进度 -->
          <el-progress v-if="uploadProgress > 0 && uploadProgress < 100" :percentage="uploadProgress" stroke-width="3"
            class="mt-3" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="basicSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改弹窗 -->
  <el-dialog v-model="dialogFormUpdate" title="修改溯源商品信息" width="50%">
    <el-form :model="Updateform" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="商品名称" prop="goodsId">
        <el-select v-model="Updateform.goodsId" placeholder="请选择商品名称" filterable>
          <el-option v-for="item in goodsOptions" :key="item.id" :label="item.goodsName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次" prop="basicBatch">
        <el-input v-model="Updateform.basicBatch" />
      </el-form-item>
      <el-form-item label="保质期(天)" prop="basicExpiration">
        <el-input v-model.number="Updateform.basicExpiration" type="number" min="0" max="99999" />
      </el-form-item>
      <el-form-item label="生产许可证号" prop="basicLicense">
        <el-input v-model="Updateform.basicLicense" />
      </el-form-item>
      <el-form-item label="生产企业" prop="basicEnterprise">
        <el-input v-model="Updateform.basicEnterprise" />
      </el-form-item>
      <!-- 商品主图上传 -->
      <el-form-item label="商品主图" prop="basicPhoto">
        <div class="upload-container">

          <el-upload class="image-uploader" action="#" :file-list="updateFileList"
            :on-change="(file, files) => handleFileChange(file, files, 'edit')" :before-upload="beforeUpload"
            :on-remove="(file, files) => handleRemove(file, files, 'edit')"
            :http-request="(options) => handleUpload(options, 'edit')" :limit="1" :on-exceed="handleExceed"
            list-type="picture-card"> <!-- 补全闭合符 -->
            <el-icon class="upload-icon">
              <Plus />
            </el-icon>
            <div class="upload-text">点击上传或拖拽文件到此处</div>
          </el-upload>

          <!-- 预览区域： -->
          <div v-if="updatePreviewUrl" class="preview-wrapper mt-3"> <!-- 改为updatePreviewUrl -->

            <el-image :src="updatePreviewUrl" fit="contain" style="width: 200px; margin-top: 10px;">
              <template #error>
                <div class="image-placeholder"><el-icon>
                    <Picture />
                  </el-icon></div>
              </template>
            </el-image>
          </div>

          <!-- 上传进度 -->
          <el-progress v-if="uploadProgress > 0 && uploadProgress < 100" :percentage="uploadProgress" stroke-width="3"
            class="mt-3" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormUpdate = false">取消</el-button>
        <el-button type="primary" @click="basicUpdate">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 导出设置弹窗 -->
  <el-dialog v-model="exportDialogVisible" title="导出设置" width="40%">
    <!-- el-card 组件：用于包裹内容，设置阴影 hover 效果，class 用于样式控制 -->
    <el-card class="barcode-card" shadow="hover">
      <div class="barcode-container">
        <!-- 表单区域：用于输入数字并验证 -->
        <el-form ref="formRefs" :model="Output" :rules="Outputrules" class="input-form">
          <el-form-item label="输入数字" prop="barcodeText">
            <el-input v-model="Output.barcodeText" placeholder="请输入要生成一维码的数字" clearable :maxlength="20">
              <template #append> <!-- 输入框后置内容，放置生成按钮 -->
                <el-button type="primary" @click="generateBarcode">
                  <el-icon>
                    <RefreshLeft /> <!-- 按钮前置图标 -->
                  </el-icon>
                  生成 <!-- 按钮文字 -->
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>

        <!-- 一维码显示区域：根据不同状态展示加载、图片、错误等内容 -->
        <div class="barcode-result">
          <!-- 加载状态：v-if 条件渲染，loading 为 true 时显示骨架屏 -->
          <el-skeleton v-if="loading" class="skeleton-loading" :loading="loading">
            <template #template> <!-- 骨架屏模板，模拟一维码占位 -->
              <div class="skeleton-barcode"></div>
            </template>
          </el-skeleton>

          <!-- 一维码生成成功：barcodeUrl 有值时渲染 -->
          <div v-else-if="barcodeUrl" class="barcode-image-container">
            <!-- 绑定图片地址，展示生成的一维码 -->
            <img :src="barcodeUrl" alt="生成的一维码" class="barcode-image" @error="handleImageError"> <!-- 图片加载失败时触发的方法 -->
          

            <!-- 下载按钮 -->
            <el-button type="success" size="small" class="download-btn" @click="downloadBarcode"><!-- 点击触发下载图片方法 -->
              <el-icon>
                <Download />
              </el-icon> <!-- 下载图标 -->
              下载图片
            </el-button>
          </div>

          <!-- 生成失败/错误状态：errorMessage 有值时渲染 -->
          <el-empty v-else-if="errorMessage" description="生成失败" class="error-state">
            <p class="error-message">{{ errorMessage }}</p> <!-- 展示具体错误信息 -->
            <el-button type="text" @click="clearError">清除错误</el-button> <!-- 清除错误状态按钮 -->
          </el-empty>

          <!-- 初始状态：未输入/未生成时渲染空提示 -->
          <el-empty v-else description="请输入数字并点击生成按钮"></el-empty>
        </div>
      </div>
    </el-card>


    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">关闭</el-button>

      </span>
    </template>
  </el-dialog>



</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElForm, ElMessageBox } from 'element-plus'
import myaxios from '@/Http/RabbitHelp'
import { useRouter } from 'vue-router'
const router = useRouter()

// const cacheKey = reactive()
// 表单数据：响应式对象，存储输入的数字
const Output = reactive({
  barcodeText: ''
});

// 表单验证规则：数组形式，每个对象对应一个校验规则
const Outputrules = {
  barcodeText: [
    {
      required: true,  // 是否必填
      message: '请输入数字',  // 校验不通过提示文案
      trigger: 'blur'  // 失去焦点时触发校验
    },
    {
      pattern: /^\d+$/,  // 正则：只能是数字
      message: '请输入纯数字',
      trigger: 'blur'
    }
  ]
};

// 响应式变量：用于状态管理
const barcodeUrl = ref('');  // 存储生成的一维码图片地址
const loading = ref(false);  // 控制加载状态
const errorMessage = ref('');  // 存储错误信息
const formRefs = ref(null);  // 表单引用，用于调用表单验证方法



/**
 * 生成一维码方法：异步函数
 */
const generateBarcode = async () => {
  // 触发表单验证，验证不通过则 return
  if (!(await formRefs.value.validate())) {
    return;
  }

  // 重置状态：清空之前的图片地址、错误信息，开始加载
  barcodeUrl.value = '';
  errorMessage.value = '';
  loading.value = true;

  try {
    const response = await myaxios.get("/api/Img/GenerateBarcode", {
      params: {
        text: Output.barcodeText
      },
      // 配置响应类型为 blob，让 axios 知道要处理二进制响应
      responseType: 'blob'
    });



    // 将响应转换为 Blob 对象（二进制大对象，用于存储图片等数据）
    // axios 已按 blob 解析，直接用 response.data 即可
    const blob = response.data;
    // 创建本地 URL 用于展示图片
    barcodeUrl.value = URL.createObjectURL(blob);

    // 提示生成成功
    ElMessage.success('一维码生成成功');
  } catch (err) {
    // 捕获错误，设置错误信息并提示
    errorMessage.value = err.message || '生成一维码时发生错误';
    ElMessage.error(errorMessage.value);
  } finally {
    // 无论成功失败，结束加载状态
    loading.value = false;
  }
};

/**
 * 处理图片加载错误方法：图片加载失败时调用
 */
const handleImageError = () => {
  errorMessage.value = '图片加载失败，请重试';  // 设置错误信息
  barcodeUrl.value = '';  // 清空图片地址
};

/**
 * 清除错误状态方法：点击“清除错误”按钮时调用
 */
const clearError = () => {
  errorMessage.value = '';  // 清空错误信息
};

/**
 * 下载一维码图片方法：点击“下载图片”按钮时调用
 */
const downloadBarcode = () => {
  // 图片地址为空时，直接返回
  if (!barcodeUrl.value) return;

  // 创建 a 标签，模拟点击下载
  const link = document.createElement('a');
  link.href = barcodeUrl.value;  // 设置下载地址
  // 拼接下载文件名，包含输入的数字
  link.download = `barcode_${form.barcodeText}.png`;
  document.body.appendChild(link);  // 添加到页面
  link.click();  // 触发点击
  document.body.removeChild(link);  // 移除 a 标签

  // 提示下载成功
  ElMessage.success('图片下载成功');
};
const handleExportSource = (id) => {
  Output.barcodeText = id
  exportDialogVisible.value = true


}

// 商品表格数据
const tableData = ref([

])
//序号
const indexMethod = (index) => {
  return index += 1
}
//分页参数
const paging = reactive({

  "pageIndex": 1,
  "pageSize": 10,
  count: 0,
  page: 1,

  "goodsName": "",
  "basicBatch": "",
  "basicExpiration": 0,
  "basicLicense": "",
  "basicEnterprise": ""

})

//查询商品信息溯源
const basicGet = () => {
  myaxios.post("/api/Goods/BasicShow", paging).then(res => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.list
      paging.count = res.data.data.count
      paging.page = res.data.data.page
      form.cacheKey = res.data.data.cacheKey
id.cacheKey=res.data.data.cacheKey
    }

  })

}
//分页
const handleSizeChange = (val) => {

  paging.pageSize = val
  basicGet()
}
const handleCurrentChange = (val) => {
  paging.pageIndex = val
  basicGet()
}

// 选中的商品ID
const selectedIds = ref([])
// 新增弹窗显隐
const dialogFormVisible = ref(false)
// 修改弹窗显隐
const dialogFormUpdate = ref(false)
// 导出设置弹窗显隐
const exportDialogVisible = ref(false)
// 删除确认弹窗显隐
const deleteDialogVisible = ref(false)
// 更多查询显隐
const isMoreQueryVisible = ref(false)
// 表单引用
const formRef = ref(null)

// 商品下拉选项
const goodsOptions = ref([

])
//查询商品名称下拉
const goodInfoGet = () => {
  myaxios.post("/api/Goods/GoodInfoGet").then(res => {
    if (res.data.code == 200) {
      goodsOptions.value = res.data.data

    }

  })

}

// 商品数据
const form = reactive({
  "goodsId": "",
  "basicBatch": "",
  "basicExpiration": 0,
  "basicLicense": "",
  "basicEnterprise": "",
  "basicPhoto": "",
  "cacheKey": ""
})

// 文件列表
const fileList = ref([])
// 商品表单验证规则
const rules = reactive({
  goodsId: [{ required: true, message: '请选择商品名称', trigger: 'change' }],
  basicBatch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { pattern: /^[0-9a-zA-Z]{1,30}$/, message: '最多支持输入30位字符', trigger: 'blur' },
  ],
  basicExpiration: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { type: 'number', message: '只能输入数字', trigger: 'blur' },
    { pattern: /^\d{1,5}$/, message: '最多支持输入5位数字', trigger: 'blur' },
  ],
  basicLicense: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { max: 30, message: '最多支持输入30个字符', trigger: 'blur' },
    { pattern: /^[0-9a-zA-Z]+$/, message: '只能输入数字、字母（包括大写、小写）', trigger: 'blur' },
  ],
  basicEnterprise: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { max: 30, message: '最多支持输入30位字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
  ],

})
// 导出表单验证规则暂未使用
const exportRules = reactive({
  exportCount: [
    { required: true, message: '请输入导出数量', trigger: 'blur' },
    { type: 'number', message: '只能输入数字', trigger: 'blur' },
    { max: 9999, message: '最多支持输入4位数字', trigger: 'blur' },
  ],
})


// 选中行变化：收集 ID
const handleSelectionChange = (selection) => {
  // 关键：确保取到正确的 id 字段（与 tableData 中的主键字段一致）
  selectedIds.value = selection.map(item => item.id);
  // 若 tableData 的主键是 id 则写 item.id，根据实际字段调整
};
// 批量删除
const handleBatchDelete = async () => {

  // 1. 校验：若未选中直接提示
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的记录！');
    return;
  }

  // 2. 调用接口：注意参数名与后端一致（如后端要 Ids 则传 Ids）
  const response = await myaxios.post('/api/Goods/BasicInfoDelRange', {
    // 若后端 Command 是 Ids，则改为 Ids: selectedIds.value
    ids: selectedIds.value,cacheKey:form.cacheKey
  });

  // 3. 处理响应
  if (response.data.code === 200) {
    ElMessage.success(response.data.message);
    // 4. 刷新表格（调用实际的查询方法，如 basicGet）
    await basicGet();
    // 5. 清空选中
    tableRef.value.clearSelection();
  } else {
    ElMessage.error(response.data.message || '删除失败');
  }

};

// 新增商品弹窗
const handleAdd = () => {
  form.goodsId = ''
  form.basicBatch = ''
  form.basicExpiration = 0
  form.basicLicense = ''
  form.basicEnterprise = ''
  form.productionEnterprise = ''
  form.basicPhoto = ''

  fileList.value = []
  dialogFormVisible.value = true
  previewUrl.value = ''
}
// 详情跳转
const handleDetail = (id, basicBatch) => {
  router.push({ path: "/traceble", query: { id, basicBatch } })

}
//商品修改数据
const Updateform = reactive({
  "id": 0,
  "goodsId": 0,
  "basicBatch": "",
  "basicExpiration": 0,
  "basicLicense": "",
  "basicEnterprise": "",
  "basicPhoto": "",
    "cacheKey": ""
})
// 新增修改弹窗专用的文件状态变量
const updateFileList = ref([])
const updatePreviewUrl = ref('')

// 修改商品弹出框，正确回显图片
const handleEdit = (row) => {
  Updateform.id = row.id
  Updateform.goodsId = row.goodsId
  Updateform.basicBatch = row.basicBatch
  Updateform.basicExpiration = row.basicExpiration
  Updateform.basicLicense = row.basicLicense
  Updateform.basicEnterprise = row.basicEnterprise
  Updateform.basicPhoto = row.basicPhoto  // 保存原始图片地址
  const baseUrl = "http://localhost:5160";
  const fullImageUrl = row.basicPhoto ? `${baseUrl}${row.basicPhoto}` : '';
  // 回显图片到修改弹窗
  updatePreviewUrl.value = fullImageUrl;

  updateFileList.value = row.basicPhoto ? [{
    url: fullImageUrl, // 使用完整URL
    name: '商品图片',
    uid: Date.now()
  }] : [];

  dialogFormUpdate.value = true
}

const id = reactive({
  id: 0,
cacheKey:""
})
// 单条删除商品信息
const handleDelete = (Id,cacheKey) => {
  id.id = Id

  ElMessageBox.confirm('确认删除该溯源商品？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      myaxios.post("/api/Goods/BasicInfoDel",id).then(res => {
        if (res.data.code == 200) {

          ElMessage.success(res.data.message)
          basicGet()
        } else {
          ElMessage.error(res.data.message)
        }

      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}


// 刷新
const refreshTable = () => {
  paging.pageIndex = 1
  paging.pageSize = 3
  basicGet()

}
// 设置暂未使用
const handleSetting = () => {
  ElMessage.info('可配置当前列表的列显示/隐藏')
}
// 更多查询暂未使用
const toggleMoreQuery = () => {
  isMoreQueryVisible.value = !isMoreQueryVisible.value
  ElMessage.info(isMoreQueryVisible.value ? '显示更多查询界面' : '隐藏更多查询界面')
}

// 上传相关状态
//预览图片
const previewUrl = ref('')
const uploadProgress = ref(0)
const isUploading = ref(false)



// 修改文件上传相关方法，支持区分新增/修改
const handleFileChange = (file, files, type = 'edit') => {
  if (file.raw) {
    if (type === 'edit') {
      updatePreviewUrl.value = URL.createObjectURL(file.raw)
    } else {

      previewUrl.value = URL.createObjectURL(file.raw)
    }
  }
}


// 上传前验证暂时未用
const beforeUpload = (file) => {
  // 验证文件类型
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isImage) {
    ElMessage.error('只能上传 JPG 或 PNG 格式的图片')
    return false
  }

  // 验证文件大小 (5MB)
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB')
    return false
  }

  return true
}

// 处理超出数量限制
const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传 1 张图片，已自动忽略多余的 ${files.length} 个文件`)
}

//上传图片
const handleUpload = async (options, type) => {
  if (isUploading.value) return
  isUploading.value = true

  try {
    const { file } = options
    const formData = new FormData()
    formData.append('imageFile', file)

    const xhr = new XMLHttpRequest()
    xhr.upload.addEventListener('progress', (e) => {
      if (e.lengthComputable) {
        uploadProgress.value = Math.round((e.loaded / e.total) * 100)
      }
    })

    const res = await myaxios.post("/api/Img/Upload/upload", formData)
    if (res.data.success) {
      // 根据类型更新对应表单的图片地址
      if (type === 'edit') {
        Updateform.basicPhoto = res.data.url
       
      } else {

        form.basicPhoto = res.data.url
        alert(form.basicPhoto)
        
      }
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '上传失败，请重试')
    if (type === 'add') {
      form.basicPhoto = ''
    } else {
      Updateform.basicPhoto = ''
    }
  } finally {
    isUploading.value = false
  }
}

//移除图片
const handleRemove = (file, files, type = 'edit') => {
  if (type === 'edit') {

    updatePreviewUrl.value = ''
    Updateform.basicPhoto = ''
  } else {
    previewUrl.value = ''
    form.basicPhoto = ''
  }
  uploadProgress.value = 0
  ElMessage.info('已移除图片')
}

// 添加商品信息
const basicSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
    
 
      myaxios.post("/api/Goods/BasicInfoAdd", form).then(res => {
        if (res.data.code == 200) {

          ElMessage.success(res.data.message)
          dialogFormVisible.value = false
          basicGet()
        } else {
          ElMessage.error(res.data.message)
        }

      })
    }



  })

}
// 修改商品信息
const basicUpdate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      Updateform.cacheKey=form.cacheKey
      myaxios.post("/api/Goods/BasicInfoUpdate", Updateform).then(res => {
        if (res.data.code == 200) {

          ElMessage.success(res.data.message)
          dialogFormUpdate.value = false
          basicGet()
        } else {
          ElMessage.error(res.data.message)
        }

      })
    }



  })

}

onMounted(() => {
  goodInfoGet()
  basicGet()
})

</script>
